"""
文件扫描与预处理模块
"""

import os
import shutil
from pathlib import Path
from typing import Dict, List, Any, Tuple
from PIL import Image
import logging
from datetime import datetime
import uuid

class FileScanner:
    """文件扫描器"""
    
    def __init__(self, config: Dict[str, Any]):
        """初始化文件扫描器"""
        self.config = config
        self.logger = logging.getLogger('image_cropping_system')
        self.supported_formats = {'.png', '.jpg', '.jpeg', '.bmp', '.tiff'}
        
        # 创建输出目录
        self.output_dir = Path('output')
        self.processed_dir = self.output_dir / 'processed'
        self.logs_dir = self.output_dir / 'logs'
        self.reports_dir = self.output_dir / 'reports'
        
        for dir_path in [self.output_dir, self.processed_dir, self.logs_dir, self.reports_dir]:
            dir_path.mkdir(parents=True, exist_ok=True)
    
    async def scan_and_classify(self, files: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """扫描并分类文件"""
        classified_files = []
        
        for file_info in files:
            try:
                # 获取文件信息
                file_path = Path(file_info.get('path', ''))
                if not file_path.exists():
                    file_path = Path('uploads') / file_info.get('path', '')
                
                if not file_path.exists():
                    self.logger.warning(f"文件不存在: {file_path}")
                    continue
                
                # 检查文件格式
                if file_path.suffix.lower() not in self.supported_formats:
                    self.logger.warning(f"不支持的文件格式: {file_path}")
                    continue
                
                # 获取图片尺寸信息
                with Image.open(file_path) as img:
                    width, height = img.size
                    aspect_ratio = width / height
                    
                    # 分类图片
                    size_category = self._classify_image_size(width, height, aspect_ratio)
                    
                    # 生成新文件名
                    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                    new_filename = f"{file_path.stem}_classified_{size_category}_{timestamp}{file_path.suffix}"
                    
                    # 复制文件到处理目录
                    processed_path = self.processed_dir / new_filename
                    shutil.copy2(file_path, processed_path)
                    
                    classified_file = {
                        'original_path': str(file_path),
                        'processed_path': str(processed_path),
                        'original_name': file_path.name,
                        'processed_name': new_filename,
                        'width': width,
                        'height': height,
                        'aspect_ratio': aspect_ratio,
                        'size_category': size_category,
                        'file_size': file_path.stat().st_size,
                        'status': 'classified'
                    }
                    
                    classified_files.append(classified_file)
                    self.logger.info(f"文件分类完成: {file_path.name} -> {size_category}")
                    
            except Exception as e:
                self.logger.error(f"处理文件 {file_info.get('path', 'unknown')} 时发生错误: {e}")
                continue
        
        return classified_files
    
    def _classify_image_size(self, width: int, height: int, aspect_ratio: float) -> str:
        """分类图片尺寸"""
        # 超宽图：宽高比 > 2.0
        if aspect_ratio > 2.0:
            return 'ultra_wide'
        
        # 超高图：宽高比 < 0.5
        elif aspect_ratio < 0.5:
            return 'ultra_tall'
        
        # 标准图：0.5 <= 宽高比 <= 2.0
        else:
            return 'standard'
    
    def get_supported_formats(self) -> List[str]:
        """获取支持的文件格式"""
        return list(self.supported_formats)
    
    def validate_file(self, file_path: Path) -> bool:
        """验证文件是否有效"""
        try:
            # 检查文件是否存在
            if not file_path.exists():
                return False
            
            # 检查文件格式
            if file_path.suffix.lower() not in self.supported_formats:
                return False
            
            # 检查文件是否可以打开
            with Image.open(file_path) as img:
                img.verify()
            
            return True
            
        except Exception as e:
            self.logger.error(f"验证文件 {file_path} 时发生错误: {e}")
            return False
    
    def get_file_info(self, file_path: Path) -> Dict[str, Any]:
        """获取文件信息"""
        try:
            stat = file_path.stat()
            
            with Image.open(file_path) as img:
                width, height = img.size
                mode = img.mode
                format_name = img.format
            
            return {
                'path': str(file_path),
                'name': file_path.name,
                'size': stat.st_size,
                'created_time': datetime.fromtimestamp(stat.st_ctime).isoformat(),
                'modified_time': datetime.fromtimestamp(stat.st_mtime).isoformat(),
                'width': width,
                'height': height,
                'mode': mode,
                'format': format_name,
                'aspect_ratio': width / height if height > 0 else 0
            }
            
        except Exception as e:
            self.logger.error(f"获取文件信息 {file_path} 时发生错误: {e}")
            return {}